go to previous page   go to home page   go to next page

Say that X.compareTo(Y)==0.

Is it then true that X.equals(Y)?

Answer:

For most classes that implement both methods this is true. But it is possible that it is not true, so check the documentation.

The compareTo() method might look only at some instance variables of an object and ignore others. The equals() method might look at different instance variables.


Consistency with equals()

If you are defining a class and writing its methods, you should probably make sure that this rule (and the previous rules) hold true. But for some classes, there might be several possible ideas of what "equals" means, and the idea picked might not not be consistent with compareTo().

Here is a program that tests some of these ideas:


class TestCompareTo
{
  public static void main ( String[] args )
  {
    String appleA = new String("apple"); // these are two distinct objects 
    String appleB = new String("apple"); // these are two distinct objects
    String berry  = new String("berry");
    String cherry = new String("cherry");
    String A, B;
    
    A = appleA; B = appleB;
    System.out.print(  A + ".compareTo(" + B + ") returns ");
    if ( A.compareTo(B) == 0) System.out.println("Zero");
    if ( A.compareTo(B) < 0 ) System.out.println("Negative");
    if ( A.compareTo(B) > 0 ) System.out.println("Positive");
    System.out.println(  A + ".equals(" + B + ") is " + A.equals(B) );
    System.out.println();
    
    A = appleA; B = berry;
    System.out.print(  A + ".compareTo(" + B + ") returns ");
    if ( A.compareTo(B) == 0) System.out.println("Zero");
    if ( A.compareTo(B) < 0 ) System.out.println("Negative");
    if ( A.compareTo(B) > 0 ) System.out.println("Positive");
    System.out.println(  A + ".equals(" + B + ") is " + A.equals(B) );
    System.out.println();
    
    A = berry; B = appleA;
    System.out.print(  A + ".compareTo(" + B + ") returns ");
    if ( A.compareTo(B) == 0) System.out.println("Zero");
    if ( A.compareTo(B) < 0 ) System.out.println("Negative");
    if ( A.compareTo(B) > 0 ) System.out.println("Positive");
    System.out.println(  A + ".equals(" + B + ") is " + A.equals(B) );
 }
}

Here is the output of the program. You might want to copy the program to a file and run it with a few more selections for A and B.

apple.compareTo(apple) returns Zero
apple.equals(apple) is true

apple.compareTo(berry) returns Negative
apple.equals(berry) is false

berry.compareTo(apple) returns Positive
berry.equals(apple) is false

If you edit the program and change some of the strings to contain upper case, the program might output mysterious results.


QUESTION 6:

(Thought Question: ) Do you think that "APPLE".compareTo("apple") returns zero?